const express = require("express");
const { Execution, ExecutionResult } = require("../db");

const router = express.Router();

router.post("/getExecutionList", async (req, res) => {
    try {
        const { executionUuid, jmxUuid, status } = req.body;
        let executions = await Execution.findAll({
            attributes: [
                ["uuid", "executionUuid"],
                ["jmx_uuid", "jmxUuid"],
                ["machine_name", "machineName"],
                ["status", "status"],
                ["created_at", "createdAt"],
                ["updated_at", "updatedAt"]
            ],
            where: {
                ...(executionUuid ? { uuid: executionUuid } : {}),
                ...(jmxUuid ? { jmx_uuid: jmxUuid } : {}),
                ...(status ? { status: status } : {})
            },
        });
        executions = executions.map(execution => execution.toJSON());
        executions.sort((execution1, execution2) => {
            if (execution1.updatedAt === execution2.updatedAt) {
                return execution2.createdAt - execution1.createdAt;
            }
            return execution2.updatedAt - execution1.updatedAt;
        });
        const response = executions;
        res.customResponse(200, "success", response);
    } catch (error) {
        console.log(error);
        res.customResponse(500, error.message, {});
    }
});

router.post("/getExecutionResults", async (req, res) => {
    try {
        const { executionUuid } = req.body;
        let executionResults = await ExecutionResult.findAll({
            attributes: [
                "uuid",
                ["round_num", "roundNumber"],
                "result",],
            where: { uuid: executionUuid },
        });
        executionResults = executionResults.map(executionResult => executionResult.toJSON());
        executionResults = executionResults.map(executionResult => {
            const result = JSON.parse(executionResult.result); 
            return { 
                uuid: executionResult.uuid,
                roundNumber: executionResult.roundNumber,
                ...result
            };
        })
        const response = executionResults;
        res.customResponse(200, "success", response);
    } catch (error) {
        console.log(error);
        res.customResponse(500, error.message, {});
    }
});

module.exports = router;
